package com.kang.controller;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttributes;

import com.alibaba.fastjson.JSON;
import com.kang.pojo.AjaxResult;
import com.kang.pojo.IntemInformation;
import com.kang.pojo.ItemDetail;
import com.kang.service.CategoryService;
import com.kang.service.InventoryService;
import com.kang.service.WarehouseService;
import com.kang.until.InventoryQueryExcelExport;
import com.kang.until.WarningPDF;
import com.vonechina.entity.page.InventoryQueryPage;
import com.vonechina.entity.page.InventoryWarningPage;
import com.vonechina.entity.page.ItemBatchPage;
import com.vonechina.entity.page.ValidityWarningPage;

/**
 * 库存管理控制层
 * @author wd
 *
 */
@Controller
@RequestMapping("inventory")
@SessionAttributes({"inventoryWarningPage","validityWarningPage","inventoryQueryPage"})
public class InventoryController extends com.kang.controller.Controller {
	/**
	 * 库存管理服务接口
	 */
	@Resource
	private InventoryService is;
	/**
	 * 类别服务层接口
	 */
	@Resource
	private CategoryService cs;
	/**
	 * 仓库服务层接口
	 */
	@Resource
	private WarehouseService ws;
	
	/**
	 * 库存管理-库存预警
	 * @param session	会话
	 * @param model	spring模型
	 * @param inventoryWarningPage	库存预警查询条件（分页封装的实体类）
	 * @return	查询相关信息去到库存预警页面
	 */
	@RequestMapping("inventoryIteminfo")
	public String inventoryIteminfo(HttpSession session,Model model,InventoryWarningPage inventoryWarningPage) {
		initRight(session);
		if (checkRight("库存预警") != SUCCESS) {
			return "basic/noRight";
		}
		//查询所有类别
		model.addAttribute("categoryList", cs.listAllCategory());
		//得到总条数
		inventoryWarningPage.setRows(is.getInventoryWarningCount(inventoryWarningPage));
		model.addAttribute("inventoryList", is.getInventoryWarningList(inventoryWarningPage));
		inventoryWarningPage.setPageUrl("inventory/inventoryIteminfo.do");
		model.addAttribute("page", inventoryWarningPage);
		return "stock/storageWarning/listStorageWarning";
	}
	
	/**
	 * 库存管理-有效期预警
	 * @param session	会话
	 * @param model	spring模型
	 * @param validityWarningPage	有效期预警查询条件-（实现分页实体类封装）
	 * @return	查询相关信息去到有效期预警页面
	 */
	@RequestMapping("validityWarning")
	public String validityWarning(HttpSession session,Model model,ValidityWarningPage validityWarningPage) {
		initRight(session);
		if (checkRight("有效期预警") != SUCCESS) {
			return "basic/noRight";
		}
		
		//查询所有类别
		model.addAttribute("categoryList", cs.listAllCategory());
		//查询所有仓库
		model.addAttribute("warehouseList", ws.listAllWarehouse());
		
		//得到总条数
		validityWarningPage.setRows(is.getValidityWarningCount(validityWarningPage));
		model.addAttribute("inventoryList", is.getValidityWarningList(validityWarningPage));
		validityWarningPage.setPageUrl("inventory/validityWarning.do");
		model.addAttribute("page", validityWarningPage);
		
		return "stock/expiryDateWarning/listValidityWarning";
	}
	
	/**
	 * 库存管理-库存查询
	 * @param session	会话
	 * @param model	Spring模型
	 * @param inventoryQueryPage	库存查询条件-封装的分页查询实体类
	 * @return	查询相关信息去到库存查询页面
	 */
	@RequestMapping("inventoryQuery")
	public String inventoryQuery(HttpSession session,Model model,InventoryQueryPage inventoryQueryPage) {
		initRight(session);
		if (checkRight("查看库存") != SUCCESS) {
			return "basic/noRight";
		}
		//查询所有类别
		model.addAttribute("categoryList", cs.listAllCategory());
		//查询所有仓库
		model.addAttribute("warehouseList", ws.listAllWarehouse());
		
		//得到总条数
		inventoryQueryPage.setRows(is.getInventoryQueryCount(inventoryQueryPage));
		model.addAttribute("inventoryList", is.getInventoryQueryList(inventoryQueryPage));

		inventoryQueryPage.setPageUrl("inventory/inventoryQuery.do");
		model.addAttribute("page", inventoryQueryPage);
		return "stock/inventoryQuery/listInventoryQuery";
	}
	
	/**
	 * 根据物品id查询所有的批次信息
	 * @param itemBatchPage	物品批次信息分页
	 * @return	物品的所有批次信息（JSON字符串）
	 */
	@RequestMapping("getAllBatchInfoById")
	@ResponseBody
	public String getAllBatchInfoById(ItemBatchPage itemBatchPage){
		AjaxResult result=new AjaxResult();
		List<ItemDetail> list = is.getAllBatchInfoById(itemBatchPage);
		result.setTotal(itemBatchPage.getRows());
		result.setRows(list);
		return JSON.toJSONString(result);
	} 
	
	
	/**
	 * 导出有效期预警PDF文件
	 * 
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping("downloadDateWarning")
	public void downloadDateWarningPDF(HttpServletResponse response, ValidityWarningPage validityWarningPage)
			throws Exception {
		//System.out.println("=============导出采购入库PDF文件===============");
		List<IntemInformation> infoList = is.getValidityWarningList(validityWarningPage);
		//此方法为直接下载文件
		//File file = WarehouseOrderPDF.buildWarehouseOrderPDF(warehouseOrder, pOrderItem);
		File file = WarningPDF.DateWarningPDF(infoList);
		if (file.isFile() && file.exists()) {
			try {
				 InputStream fis = new BufferedInputStream(new FileInputStream(file));
				    byte[] buffer = new byte[fis.available()];
				    fis.read(buffer);
				    fis.close();
				    response.reset();
				    //乱码处理
				    //先去掉文件名称中的空格,然后转换编码格式为utf-8,保证不出现乱码,这个文件名称用于浏览器的下载框中自动显示的文件名
				    response.addHeader("Content-Disposition", "attachment;filename=" + new String(file.getName().replaceAll(" ", "").getBytes("utf-8"),"iso8859-1"));
				    response.addHeader("Content-Length", "" + file.length());
				    OutputStream os = new BufferedOutputStream(response.getOutputStream());
				    response.setContentType("application/octet-stream");
				    os.write(buffer);//输出文件
				    os.flush();
				    os.close();//关闭流，释放资源！
			} catch (Exception e) {
				e.printStackTrace();
			}
			file.delete();
		}
	}
	
	/**
	 * 导出有效期预警PDF文件
	 * 
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping("downloadStorageWarning")
	public void downloadStorageWarningPDF(HttpServletResponse response, InventoryWarningPage inventoryWarningPage)
			throws Exception {
		List<IntemInformation> infoList = is.getInventoryWarningList(inventoryWarningPage);
		//此方法为直接下载文件
		File file = WarningPDF.StorageWarningPDF(infoList);
		if (file.isFile() && file.exists()) {
			try {
				 InputStream fis = new BufferedInputStream(new FileInputStream(file));
				    byte[] buffer = new byte[fis.available()];
				    fis.read(buffer);
				    fis.close();
				    response.reset();
				    //乱码处理
				    //先去掉文件名称中的空格,然后转换编码格式为utf-8,保证不出现乱码,这个文件名称用于浏览器的下载框中自动显示的文件名
				    response.addHeader("Content-Disposition", "attachment;filename=" + new String(file.getName().replaceAll(" ", "").getBytes("utf-8"),"iso8859-1"));
				    response.addHeader("Content-Length", "" + file.length());
				    OutputStream os = new BufferedOutputStream(response.getOutputStream());
				    response.setContentType("application/octet-stream");
				    os.write(buffer);//输出文件
				    os.flush();
				    os.close();//关闭流，释放资源！
			} catch (Exception e) {
				e.printStackTrace();
			}
			file.delete();
		}
	}
	
	/**
	 * 导出库存查询Excel文件
	 * @param 
	 * @throws
	 */
	@RequestMapping("downloadExcel")
	public void downloadPurchaseAgentExcel(HttpServletRequest request, HttpServletResponse response, InventoryQueryPage inventoryQueryPage) 
			throws Exception {
		
		List<IntemInformation> iinfoList = is.getInventoryQueryList(inventoryQueryPage);
		
		//此方法为直接下载文件
		File file = InventoryQueryExcelExport.buildInventoryQueryExcel(request, response, iinfoList);
		if (file.isFile() && file.exists()) {
			try {
				 InputStream fis = new BufferedInputStream(new FileInputStream(file));
				    byte[] buffer = new byte[fis.available()];
				    fis.read(buffer);
				    response.reset();
				    //乱码处理
				    //先去掉文件名称中的空格,然后转换编码格式为utf-8,保证不出现乱码,这个文件名称用于浏览器的下载框中自动显示的文件名
				    response.addHeader("Content-Disposition", "attachment;filename=" + new String(file.getName().replaceAll(" ", "").getBytes("utf-8"),"iso8859-1"));
				    response.addHeader("Content-Length", "" + file.length());
				    OutputStream os = new BufferedOutputStream(response.getOutputStream());
				    response.setContentType("application/octet-stream");
				    os.write(buffer);//输出文件
				    os.flush();
				    os.close();//关闭流，释放资源！
				    fis.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
			file.delete();
		}
		
	}

	
}
